"""
托盘与图标
"""
import os
import sys
import threading
import pystray
from pystray import Menu, MenuItem
from PIL import Image
import tkinter as tk

abs_static_resource_path = lambda f: os.path.abspath(
    os.path.join(os.path.dirname(__file__), f)
)


class TrayIcon:
    def quit_window(self, icon: pystray.Icon):
        icon.stop()
        self.main_window.destroy()

    def on_exit(self):
        sys.exit()
        self.main_window.withdraw()

    def show_window(self):
        self.main_window.deiconify()

    def __init__(self, main_window: tk.Tk) -> None:
        self.main_window = main_window
        self.menu = (
            MenuItem("显示主界面", self.show_window, default=True),
            # Menu.SEPARATOR,
            MenuItem("退出程序", self.quit_window),
        )
        self.image = Image.open(abs_static_resource_path("static/icon.png"))
        self.icon = pystray.Icon("icon", self.image, "文档文本搜索工具", self.menu)

        self.th = threading.Thread(target=self.icon.run, daemon=True).start()
